import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout/index.vue'
import HomeIndex from '@/views/layout/home.vue'
import CategoryIndex from '@/views/layout/category.vue'
import CartIndex from '@/views/layout/cart.vue'
import UserIndex from '@/views/layout/user.vue'

import store from '@/store'

const Search = () => import('@/views/search/index.vue')
const Prodatail = () => import('@/views/prodetail/index.vue')
const Pay = () => import('@/views/pay/index.vue')
const Login = () => import('@/views/login/index.vue')
const Myorder = () => import('@/views/myorder/index.vue')
const SearchList = () => import('@/views/search/list.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: HomeIndex
        },
        {
          path: '/category',
          component: CategoryIndex
        },
        {
          path: '/cart',
          component: CartIndex
        },
        {
          path: '/user',
          component: UserIndex
        }
      ]
    },
    {
      path: '/search',
      component: Search
    },
    {
      path: '/prodetail/:id?',
      component: Prodatail
    },
    {
      path: '/pay',
      component: Pay
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/myorder',
      component: Myorder
    },
    {
      path: '/searchlist',
      component: SearchList
    }
  ],
  mode: 'history'
})

// 所有的路由在真正被访问到之前，都会先经过全局全局前置守卫
// 只有全局前置守卫放行了，才会到达对应的页面
// 全局前置导航守卫
// to：到哪去，到哪去的完整路由信息对象（路径，参数）
// from：从哪里来，从哪来的路由信息对象
// next():是否放行
// （1）next()直接放行，放行到to要去的路径
// （2）next(路径)进行拦截，拦截到next里面配置的路径
const authUrls = ['/user', '/myorder']
router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  const token = store.getters.token
  console.log(token)
  if (token) {
    next()
  } else {
    next({
      path: '/login',
      query: {
        ...to.query,
        backUrl: to.fullPath
      }
    })
  }
})
export default router
